package com.myapp.ruyixing.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.Config;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.ShopList;
import com.myapp.ruyixing.model.ShopList.Shop;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.BitmapLruCache;

public class ShopListActivity extends Activity implements OnItemClickListener {

	private ShopListAdapter mAdapter;
	private ArrayList<Shop> mShopList;
	private ListView mListView;

	private RYHttpResponseHandler mHttpResponseHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			try {
				ShopList shopList = (ShopList) o;
				onLoadingDataFinished(true, shopList);
			} catch (Exception e) {
				onLoadingDataFinished(false, null);
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			onLoadingDataFinished(false, null);
		}
	};

	public static void startShopListActivity(Context context, String foodname) {
		if (context == null || TextUtils.isEmpty(foodname)) {
			return;
		}
		Intent intent = new Intent(context, ShopListActivity.class);
		intent.putExtra("foodname", foodname);
		context.startActivity(intent);
	}

	private void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	private void onLoadingDataStarted(String cityid, String foodname, int pn,
			int rn, double lat, double lon) {
		((TitleBar) findViewById(R.id.title_bar)).showLoading(true);
		RYHttpClient.getShopList(this, mHttpResponseHandler, cityid, foodname,
				pn, rn, lat, lon);
	}

	private void onLoadingDataFinished(boolean succeed, ShopList shopList) {
		((TitleBar) findViewById(R.id.title_bar)).showLoading(false);
		if (succeed && shopList != null) {
			if (shopList.list != null && shopList.list.size() > 0) {
				mShopList.clear();
				mShopList.addAll(shopList.list);
				mAdapter.notifyDataSetChanged();
			} else {
				showToast("此城市无美食数据！");
			}
		} else {
			showToast("加载美食列表失败！");
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shop_list);
		((TitleBar) findViewById(R.id.title_bar))
				.setOnIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onBackPressed();
					}
				});

		String foodname = getIntent().getStringExtra("foodname");
		if (TextUtils.isEmpty(foodname)) {
			finish();
			return;
		}
//		((TextView) findViewById(R.id.location)).setText(Config.sMyLocation
//				.getStreet());
		((TextView) findViewById(R.id.location)).setVisibility(View.GONE);

		mListView = (ListView) findViewById(R.id.list);
		mShopList = new ArrayList<Shop>();
		mAdapter = new ShopListAdapter();
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
		onLoadingDataStarted(Config.sCityId, foodname, 0, 10,
				Config.sMyLocation.getLatitude(),
				Config.sMyLocation.getLongitude());
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
		if (id >= 0 && mShopList != null && id < mShopList.size()) {
			ShopDetailActivity.startShopDetailActivity(this,
					mShopList.get((int) id).id);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.shop_list, menu);
		return true;
	}

	private class ShopListAdapter extends BaseAdapter {

		private class ViewHolder {
			public TextView mShopName;
			public TextView mAverageCost;
			public TextView mDistance;
			public TextView mKeyWords;
			public NetworkImageView mShopImage;
			public ImageView mScoreView;
		}

		private RequestQueue mQueue;
		private ImageLoader mImageLoader;

		public ShopListAdapter() {
			super();
			mQueue = Volley.newRequestQueue(ShopListActivity.this);
			mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());
		}

		@Override
		public int getCount() {
			return mShopList == null ? 0 : mShopList.size();
		}

		@Override
		public Object getItem(int position) {
			return mShopList == null ? null : mShopList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			Shop shop = (Shop) getItem(position);
			if (shop == null) {
				return convertView;
			}
			if (convertView == null) {
				convertView = LayoutInflater.from(ShopListActivity.this)
						.inflate(R.layout.shop_list_item, parent, false);
				holder = new ViewHolder();
				holder.mAverageCost = (TextView) convertView
						.findViewById(R.id.text_average_cost);
				holder.mDistance = (TextView) convertView
						.findViewById(R.id.text_distance);
				holder.mKeyWords = (TextView) convertView
						.findViewById(R.id.text_keywords);
				holder.mShopName = (TextView) convertView
						.findViewById(R.id.text_shop_name);
				holder.mShopImage = (NetworkImageView) convertView
						.findViewById(R.id.image_shop);
				holder.mScoreView = (ImageView) convertView
						.findViewById(R.id.score);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.mScoreView.setImageLevel(shop.score);
			if (!TextUtils.isEmpty(shop.averagecost)) {
				holder.mAverageCost.setText(getString(R.string.average_cost)
						+ shop.averagecost);
			}
			if (!TextUtils.isEmpty(shop.name)) {
				holder.mShopName.setText(shop.name);
			}
			if (!TextUtils.isEmpty(shop.keywords)) {
				holder.mKeyWords.setText(shop.keywords);
			}
			if (shop.distance >= 0) {
				String distance = "";
				if (shop.distance >= 1000) {
					if (shop.distance >= 1000000) {
						distance = "999+km";
					} else {
						distance = String.format("%.1fkm",
								((double) shop.distance) / 1000);
					}
				} else {
					distance = shop.distance + "m";
				}
				holder.mDistance.setText(distance);
			}
			if (!TextUtils.isEmpty(shop.picurl)) {
				holder.mShopImage.setImageUrl(shop.picurl, mImageLoader);
			}
			return convertView;
		}
	}

}
